package org.javaforever.cookieshop.shiro;

import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.fastjson.JSON;

public class SimpleFormAuthenticationFilter extends FormAuthenticationFilter {

    private static final Logger log = LoggerFactory.getLogger(SimpleFormAuthenticationFilter.class);
    
    public SimpleFormAuthenticationFilter() {
        super();
    }
    
    @Override
    public boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        //Always return true if the request's method is OPTIONS
        if (request instanceof HttpServletRequest) {
            if (((HttpServletRequest) request).getMethod().toUpperCase().equals("OPTIONS")) {
                return true;
            }
        }
        return super.isAccessAllowed(request, response, mappedValue);
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
            HttpServletResponse res = (HttpServletResponse)response;
            res.setHeader("Access-Control-Allow-Origin", "true");
            res.setContentType("application/json; charset=utf-8");
            res.setStatus(HttpServletResponse.SC_OK);
            PrintWriter writer = res.getWriter();
            Map<String, Object> map= new HashMap<>();
            map.put("success", false);
            map.put("noAuth", true);
            map.put("error", "无权限");
            writer.write(JSON.toJSONString(map));
            writer.close();
            //return false 拦截， true 放行
            return false;
    }

    /*
    * 判断ajax请求
    * @param request
    * @return
    */
    boolean isAjax(HttpServletRequest request){
        return  (request.getHeader("X-Requested-With") != null  && "XMLHttpRequest".equals( request.getHeader("X-Requested-With").toString())   ) ;
    }

}
